/*
 *所有关于MES_Bom_Main类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*MES_Bom_MainService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using VolPro.Core.BaseProvider;
using VolPro.Core.Enums;
using VolPro.Core.Extensions;
using VolPro.Core.Extensions.AutofacManager;
using VolPro.Core.ManageUser;
using VolPro.Core.Services;
using VolPro.Core.Utilities;
using VolPro.Entity.DomainModels;
using VolPro.MES.IRepositories;

namespace VolPro.MES.Services
{
    public partial class MES_Bom_MainService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IMES_Bom_MainRepository _repository;//访问数据库

        WebResponseContent webResponse = new WebResponseContent();

        [ActivatorUtilitiesConstructor]
        public MES_Bom_MainService(
            IMES_Bom_MainRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        /// <summary> 
        /// 查询装机BOM
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="bomid"></param> 
        /// <returns></returns>
        public async Task<WebResponseContent> ListBoms(dynamic obj)
        {
            WebResponseContent responseContent = new WebResponseContent();
            try
            {
                if (!string.IsNullOrEmpty(IsPropertyExists(obj, "bomid")))
                {
                    string d = obj.bomid;
                    var bid = Guid.Parse(d);
                    responseContent.Code = "200";
                    responseContent.OK("成功", GetBom(bid, true));
                }
                else if (IsPropertyExists(obj, "productCode") != string.Empty)
                {
                    ///////////////////序列号查找 计划详情 得到bomid
                    string d = obj.productCode;
                    //var _bomid = _repository.DbContext.Queryable<MES_ProductionPlanDetail>().Where(it => it.MaterialCode == d).First();
                    var _bomid = await _repository.DbContext.Set<MES_ProductionPlanDetail>().FirstOrDefaultAsync(b => b.MaterialCode == d);
                    if (_bomid == null || _bomid.MaterialCode == null)
                    {
                        responseContent.Data = null;
                        responseContent.Code = "200";
                        responseContent.OK("无生产任务");
                    }
                    else
                    {
                        responseContent.Code = "200";
                        responseContent.OK("成功", GetBom(Guid.Parse(_bomid.BomId), true));
                    }
                }
            }
            catch (Exception ex)
            {
                responseContent.Code = "500";
                responseContent.OK(ex.Message);
            }
            finally
            {
                //    if (!string.IsNullOrEmpty(responseContent.Code))
                //    {
                //        //memoryCache.Remove(loginInfo.UUID);
                //    }
                Logger.Info(LoggerType.Login, webResponse.Message, $"ListBoms -Body:{obj.ToString()},UserName:{UserContext.Current.UserName}", null);
            }
            return responseContent;
        }
        /// <summary>
        /// 获取全部bom详情/工位bom详情
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        private List<object> GetBom(Guid guid, bool isAll)
        {
            List<object> list = new List<object>();
            try
            {
                var opBomlist = _repository.DbContext.Set<MES_Bom_Detail>().AsNoTracking().Where(b => b.BomId == guid).ToList();
                list.Add(opBomlist);
                if (isAll)
                {
                    int userId = UserContext.Current.UserId;
                    var opid = _repository.DbContext.Set<MES_UserPost>().FirstOrDefault(it => it.UserId == userId);
                    //var opid = _repository.DbContext.Queryable<MES_UserPost>().Where(it => it.UserId == userId).First();
                    //opBomlist = _repository.DbContext.Set<MES_Bom_Detail>().FirstOrDefault(it => it.ProcessID == guid.ToString());
                   var opBomlistOP = _repository.DbContext.Set<MES_Bom_Detail>().AsNoTracking().Where(b => b.ProcessID == guid.ToString()).ToList();
                    //opBomlist = _repository.DbContext.Queryable<MES_Bom_Detail>().Where(it => it.ProcessID == guid).ToList();
                    list.Add(opBomlistOP);
                }
            }
            catch (Exception ex)
            {
            }
            return list;
        }
        ////private bool IsPropertyExists(dynamic obj, string propertyName)
        ////{
        ////    if (!(obj is IDictionary<string, object> dict))
        ////        return false;

        ////    return dict.Keys.Any(k => string.Equals(k, propertyName, StringComparison.OrdinalIgnoreCase));
        ////}

        ////public bool IsPropertyExists(dynamic obj, string propertyName)
        ////{
        ////    if (obj == null) return false;

        ////    Type type = obj.GetType();
        ////    foreach (var prop in type.GetRuntimeProperties())
        ////    {
        ////        if (string.Equals(prop.Name, propertyName, StringComparison.OrdinalIgnoreCase))
        ////            return true;
        ////    }
        ////    return false;
        ////}
        private string IsPropertyExists(dynamic obj, string propertyName)
        {
            string d = string.Empty;
            try
            {
                d = obj[propertyName];
            }
            catch (Exception)
            {

            }
            return d;
        }
    }
}
